#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/CI/lib -I/data/Software/mydan/CI/private/lib
use strict;
use warnings;
use FindBin qw( $RealBin );
use Util;
use Logs;
use JobHash;
use POSIX ":sys_wait_h";

$| ++;

=head1 SYNOPSIS

    db => $mysql,

=cut

return sub
{
    my %param = @_;

    my ( $db, $interval, $logs, $myname ) = ( $param{db}, 10, Logs->new( 'build' ), Util::myname() );
    my ( $count, %count ) = int time / $interval;

    $SIG{'CHLD'} = sub {
        while((my $pid = waitpid(-1, WNOHANG)) >0)
        {
            my $code = ( $? == -1 || $? & 127 ) ? 110 : $? >> 8;
            print "chld: $pid exit $code.\n";;
        }
    };

    while( 1 )
    {
        warn "do ...\n";
        my $time = time;
        my $counttmp = int time / $interval;
        ( $count, %count ) = ( $counttmp ) if $count ne $counttmp;

        my $x = eval{ $db->query( "select projectid,uuid from `version` where status='init' and pid is null and projectid not in ( select projectid from `version` where status='running') order by id" ) };
        $logs->die( "mysql query fail: $@" ) if $@;
        $logs->die( "get project list from mysql fail" ) unless defined $x && ref $x eq 'ARRAY';

        my %running;
        
        my $jobhash = JobHash->new( $db );

        for ( @$x )
        {
            my ( $projectid, $uuid ) = @$_;
            next if $running{$projectid};
            next unless $jobhash->hash( $projectid );
            print "do $uuid\n";
            $running{$projectid} = 1;
            unless( fork() )
            {
                $logs->say( "build $uuid" );
                $ENV{CI_BUILD_UUID} = "XXX${uuid}XXX";
                open STDOUT, '>', "$RealBin/../logs/build/$uuid" or $logs->die( "Can't open 'logs/build/$uuid': $!" );
                open (STDERR, ">&STDOUT") or $logs->die( "open STDERR failed: $uuid" );
                my $tsocks = -e "/usr/bin/tsocks" ? "/usr/bin/tsocks " : '';
                exec "$tsocks$RealBin/../bin/build -uuid $uuid";
            }
            warn "start build $uuid\n";
        }

        sleep 3;
    }
}
